/**
 * 
 */
package com.jushu.storbox.service;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;

import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.callback.IDownloadThumbnailCallback;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileInfo;
import com.jushu.storbox.entities.FolderInfo;
import com.jushu.storbox.task.tqueue.DownloadThumbnailTask;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.vo.PagedList;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.model.request.AsyncTaskINodeRequest;
import com.huawei.sharedrive.sdk.android.model.request.AsyncTaskRequest;
import com.huawei.sharedrive.sdk.android.modelV2.request.CopyFileRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.FolderListRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.FolderSearchRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.MoveFileRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.request.Order;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderListResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderResponse;
import com.huawei.sharedrive.sdk.android.modelV2.response.ServerUrlV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.UserResponseV2;
import com.huawei.sharedrive.sdk.android.service.handler.AsyncTaskHandler;
import com.huawei.sharedrive.sdk.android.serviceV2.FileClientV2;
import com.huawei.sharedrive.sdk.android.serviceV2.FolderClientV2;
import com.huawei.sharedrive.sdk.android.serviceV2.UserClientV2;

public class RemoteFileService extends AbstractBaseService implements IRemoteFileService
{
    
    private final static String TAG = "RemoteFileService";
    
    private boolean isChange = false;
    
    UserClientV2 userClient = ShareDriveApplication.getInstance().getUserClientV2();
    
    FileClientV2 fileClient = FileClientV2.getInstance();
    
    /**
	 * 
	 */
    public RemoteFileService()
    {
        // TODO Auto-generated constructor stub
    }
    
    @Override
    public FileInfoResponseV2 getFileResponse(FileFolderInfo info) throws ClientException
    {
        return fileClient.getFileInfo(info.getOwnerId(), info.getId(), this.getAuthCode());
    }
    
    @Override
    public FileInfoResponseV2 renameFile(FileFolderInfo node, String name) throws ClientException
    {
        return fileClient.renameFile(node.getOwnerId(), node.getId(), this.getAuthCode(), name);
    }
    
    @Override
    public String deleteFile(FileFolderInfo fileFolderInfo) throws ClientException
    {
    	shareDriveApplication.smartAuthorization();
    	
        String response = null;
        response = fileClient.deleteFile(fileFolderInfo.getOwnerId(), fileFolderInfo.getId(), this.getAuthCode());
        return response;
    }
    
    @Override
    public void deleteFileAsync(final FileFolderInfo fileFolderInfomation, AsyncTaskHandler handler) throws ClientException
    {
    	Long ownerId = Long.valueOf(fileFolderInfomation.getOwnerId());
    	Long fileId = Long.valueOf(fileFolderInfomation.getId());
    	shareDriveApplication.smartAuthorization();
    	AsyncTaskRequest fileToDeleteRequest = new AsyncTaskRequest();
        fileToDeleteRequest.setType("delete");
        fileToDeleteRequest.setSrcOwnerId(ownerId);
        
        ArrayList<AsyncTaskINodeRequest> fileToDeleteList = new ArrayList<AsyncTaskINodeRequest>();
        AsyncTaskINodeRequest fileToDelete = new AsyncTaskINodeRequest(fileId);
        fileToDeleteList.add(fileToDelete);
        
        fileToDeleteRequest.setSrcNodeList(fileToDeleteList);
        fileClient.deleteFileAsy(ShareDriveApplication.getInstance().getAuthorization(), 
        		fileToDeleteRequest, handler);
    }
    
    @Override
    public String moveFile(FileFolderInfo file, FileFolderInfo targetFolder) throws ClientException
    {
    	String targetFolderId = "0";
    	if(targetFolder != null) {
    		targetFolderId = targetFolder.getId();
    	}
    	
		MoveFileRequestV2 request = new MoveFileRequestV2();
		request.setDestParent(Long.valueOf(targetFolderId));
		request.setAutoRename(true);
		request.setDestOwnerId(Long.valueOf(file.getOwnerId()));
		
    	shareDriveApplication.smartAuthorization();
        return fileClient.moveFile(file.getOwnerId(), file.getId(), request, this.getAuthCode());
    }
    
    @Override
    public FileInfoResponseV2 copyFile(String resourceOwnerId, String resourceId, CopyFileRequestV2 request) throws ClientException
    {
    	//request server do task
		FileInfoResponseV2 response = FileClientV2.getInstance().copyFile(resourceOwnerId, resourceId, 
			ShareDriveApplication.getInstance().getAuthorization(), request);
        return response;
    }
    
    @Override
    public List<FileFolderInfo> searchRemote(Context context, int limit, int offset, String name)
        throws ClientException
    {
    	shareDriveApplication.smartAuthorization();
        FolderSearchRequestV2 request = new FolderSearchRequestV2();
        // request.setLimit(limit);
        request.setName(name);
        // request.setOffset(offset);
        request.setOwnerID(ShareDriveApplication.getInstance().getWnerID());
        FolderListResponseV2 response = FolderClientV2.getInstance().search(request,
            ShareDriveApplication.getInstance().getAuthorization());
        List<FileFolderInfo> folderList = FileHelper.convertFolderRemoteToLocal(response);
        List<FileFolderInfo> fileList = FileHelper.convertFileRemoteToLocal(response);
        folderList.addAll(fileList);
        return folderList;
    }
    
    @Override
    public List<FileFolderInfo> getMoveFolderList(Context context, String ownerId, String folderID, String des, int limit,
        int offset, String orderby) throws ClientException
    {
    	shareDriveApplication.smartAuthorization();
        List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
        List<FolderInfo> folderInfoList = null;
        List<FileInfo> fileInfoList = null;
        long lastRefreshTime = DAOFactory.instance(context).getFolderDao().getLastRefreshTime(ownerId, folderID);
        long nowTime = System.currentTimeMillis();
        SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
        boolean isOnline = settings.getBoolean(ClientConfig.INTERNETSTATE, false);
        boolean autoManualFlag = false;
        if (isOnline && (!autoManualFlag || (ClientConfig.REFRESH_TIME < nowTime - lastRefreshTime)))
        {
            LogUtil.i(TAG, "Get server file&folder list...");
            FolderListRequestV2 request = new FolderListRequestV2();
            request.setFolderID(folderID);
            request.setLimit(limit);
            request.setOffset(offset);
            request.setOwnerID(ownerId);
            
            Order o = new Order();
            o.setDirection(des);
            o.setField(orderby);
            List<Order> olist = new ArrayList<Order>();
            olist.add(o);
            request.setOrder(olist);
            
            final FolderListResponseV2 response = FolderClientV2.getInstance().getFolderInfoList(request,
                this.getAuthCode());
            
            List<FileFolderInfo> folderList = FileHelper.convertFolderRemoteToLocal(response);
            fileFolderInfoList.addAll(folderList);
            folderInfoList = DAOFactory.instance(context).getFolderDao().getFolderList(ownerId, folderID);
            fileInfoList = DAOFactory.instance(context).getFileDao().getFileList(ownerId, folderID);
            FileHelper.compareServiceClientFolder(context, response.getFolders(), folderInfoList, ownerId,folderID);
            FileHelper.compareServiceClientFile(context, response.getFiles(), fileInfoList, ownerId, folderID);
            DAOFactory.instance(context).getFolderDao().updateLastRefreshTime(ownerId, folderID, nowTime);
        }
        fileFolderInfoList.clear();
        folderInfoList = DAOFactory.instance(context).getFolderDao().getFolderList(ownerId, folderID);
        fileFolderInfoList.addAll(folderInfoList);
        
        return fileFolderInfoList;
        
    }
    
    @Override
    public synchronized List<FileFolderInfo> getFileFolderList(boolean autoManualFlag, Context context,
    		String ownerId, String folderID, String des, int limit, int offset, String orderby) throws ClientException
    {
    	shareDriveApplication.smartAuthorization();
        List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
        List<FolderInfo> folderInfoList = null;
        List<FileInfo> fileInfoList = null;
        long lastRefreshTime = DAOFactory.instance(context).getFolderDao().getLastRefreshTime(ownerId, folderID);
        long nowTime = System.currentTimeMillis();
        SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
        boolean isOnline = settings.getBoolean(ClientConfig.INTERNETSTATE, false);
        if (isOnline && (!autoManualFlag || (ClientConfig.REFRESH_TIME < nowTime - lastRefreshTime)))
        {
            FolderListRequestV2 request = new FolderListRequestV2();
            request.setFolderID(folderID);
            request.setLimit(limit);
            request.setOffset(offset);
            request.setOwnerID(ownerId);
            
            Order o = new Order();
            o.setDirection(des);
            o.setField(orderby);
            List<Order> olist = new ArrayList<Order>();
            olist.add(o);
            request.setOrder(olist);
            
            final FolderListResponseV2 response = FolderClientV2.getInstance().getFolderInfoList(request,
                this.getAuthCode());
            
            List<FileFolderInfo> folderList = FileHelper.convertFolderRemoteToLocal(response);
            List<FileFolderInfo> fileList = FileHelper.convertFileRemoteToLocal(response);
            fileFolderInfoList.addAll(folderList);
            fileFolderInfoList.addAll(fileList);
            folderInfoList = DAOFactory.instance(context).getFolderDao().getFolderList(ownerId, folderID);
            fileInfoList = DAOFactory.instance(context).getFileDao().getFileList(ownerId, folderID);
            FileHelper.compareServiceClientFolder(context, response.getFolders(), folderInfoList, ownerId, folderID);
            FileHelper.compareServiceClientFile(context, response.getFiles(), fileInfoList, ownerId, folderID);
            DAOFactory.instance(context).getFolderDao().updateLastRefreshTime(ownerId, folderID, nowTime);
        }
        fileFolderInfoList.clear();
        folderInfoList = DAOFactory.instance(context).getFolderDao().getFolderList(ownerId, folderID);
        fileFolderInfoList.addAll(folderInfoList);
        fileInfoList = DAOFactory.instance(context).getFileDao().getFileList(ownerId, folderID);
        fileFolderInfoList.addAll(fileInfoList);
        
        return fileFolderInfoList;
    }
    
    @Override
    public synchronized List<FileFolderInfo> getFileFolderListPage(boolean autoManualFlag,
        final Context context, final String ownerId, final String folderID, String des, String orderby, Handler handler)
    {
        List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
        // List<FolderInfo> folderInfoList = null;
        // List<FileInfo> fileInfoList = null;
        long lastRefreshTime = DAOFactory.instance(context).getFolderDao().getLastRefreshTime(ownerId, folderID);
        long nowTime = System.currentTimeMillis();
        SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
        boolean isOnline = settings.getBoolean(ClientConfig.INTERNETSTATE, false);
        if (isOnline && (!autoManualFlag || (ClientConfig.REFRESH_TIME < nowTime - lastRefreshTime)))
        {
            LogUtil.i(TAG, "Get server file&folder list...");
            fileFolderInfoList = getServerFileFolderListPage(context,ownerId,
                folderID,
                des,
                orderby,
                fileFolderInfoList,
                nowTime,
                handler);
            
            if (null != fileFolderInfoList)
                return fileFolderInfoList;
        }
        fileFolderInfoList.clear();
        List<FolderInfo> folderInfoList = DAOFactory.instance(context)
            .getFolderDao()
            .getFolderListPage(Constant.MYCLOUD_GET_FILE_LIST_STATE, ownerId, folderID, des, orderby);
        fileFolderInfoList.addAll(folderInfoList);
        List<FileInfo> fileInfoList = DAOFactory.instance(context)
            .getFileDao()
            .getFileListPage(ownerId, folderID, Constant.MYCLOUD_GET_FILE_LIST_STATE, des, orderby);
        fileFolderInfoList.addAll(fileInfoList);
        if (null == fileFolderInfoList || 0 == fileFolderInfoList.size())
        {
            fileFolderInfoList = getServerFileFolderListPage(context,ownerId, 
                folderID,
                des,
                orderby,
                fileFolderInfoList,
                nowTime,
                handler);
        }
        return fileFolderInfoList;
    }
    
    /***
     * @param folderisChange
     * @param fileIsChange
     * @return
     */
    public void setResourceIsChange(boolean folderisChange, boolean fileIsChange)
    {
        isChange = false;
        LogUtil.i(TAG, "folderisChange:[setResourceIsChange]" + folderisChange);
        isChange = folderisChange || fileIsChange;
    }
    
    @Override
    public boolean getResourceIsChange()
    {
        return this.isChange;
    }
    
    @Override
    public List<FileFolderInfo> getFileFolderListFromServer(final Context context, String ownerId, String folderID,
    		String des, String orderby, Handler handler) throws ClientException
    		{
    	shareDriveApplication.smartAuthorization();
    	List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
    	long currentTimeMillis = System.currentTimeMillis();
    	DAOFactory.instance(context).getFolderDao().updateLastRefreshTime(ownerId, folderID, currentTimeMillis);
    	List<FolderInfo> folderInfoList = new ArrayList<FolderInfo>();
    	List<FileInfo> fileInfoList = new ArrayList<FileInfo>();
    	
    	FolderListRequestV2 request = new FolderListRequestV2();
    	request.setFolderID(folderID);
    	request.setLimit(ClientConfig.CLOUD_COUNT_PER_PAGE);
    	request.setOffset(ClientConfig.CLOUD_COUNT_offset);
    	request.setOwnerID(ownerId);
    	
    	Order o = new Order();
    	o.setDirection(des);
    	o.setField(orderby);
    	List<Order> olist = new ArrayList<Order>();
    	olist.add(o);
    	request.setOrder(olist);
    	final FolderListResponseV2 response = FolderClientV2.getInstance().getFolderInfoList(request,
    			this.getAuthCode());
    	
    	if (null != response)
    	{
    		folderInfoList = DAOFactory.instance(context)
    				.getFolderDao()
    				.getFolderListPage(Constant.MYCLOUD_GET_FILE_LIST_STATE, ownerId, folderID, des, orderby);
    		
    		fileInfoList = DAOFactory.instance(context)
    				.getFileDao()
    				.getFileListPage(ownerId,folderID, Constant.MYCLOUD_GET_FILE_LIST_STATE, des, orderby);
    		boolean fileIsChanged = false;
    		boolean folderIsChanged = false;
    		if (null != response.getFolders())
    		{
    			folderIsChanged = FileHelper.compareServiceClientFolder(context,
    					response.getFolders(),
    					folderInfoList, ownerId, folderID);
    			LogUtil.i(TAG, "the folder "+folderID+"is change ? "+folderIsChanged);
    		}
    		if (null != response.getFiles())
    		{
    			fileIsChanged = FileHelper.compareServiceClientFile(context,
    					response.getFiles(),
    					fileInfoList,
    					ownerId, folderID);
    		}
    		setResourceIsChange(folderIsChanged, fileIsChanged);
    	}
    	
    	if ("0".equals(folderID))
    	{
    		FolderInfo folderInfo = new FolderInfo();
    		folderInfo.setId(folderID);
    		folderInfo.setOwnerBy(ShareDriveApplication.getInstance().getWnerID());
    		folderInfo.setLastRefreshTime(currentTimeMillis);
    		DAOFactory.instance(context).getFolderDao().insertOrUpdateFolder(folderInfo, context);
    	}
    	fileFolderInfoList.clear();
    	folderInfoList = DAOFactory.instance(context)
    			.getFolderDao()
    			.getFolderListPage(Constant.MYCLOUD_GET_FILE_LIST_STATE, ownerId, folderID, des, orderby);
    	fileFolderInfoList.addAll(folderInfoList);
    	fileInfoList = DAOFactory.instance(context)
    			.getFileDao()
    			.getFileListPage(ownerId, folderID, Constant.MYCLOUD_GET_FILE_LIST_STATE, des, orderby);
    	fileFolderInfoList.addAll(fileInfoList);
    	
    	return fileFolderInfoList;
    };
    
    
    @Override
    public PagedList<FileFolderInfo> searchNodeListFromServer(final Context context, String ownerId, String keyWords,
    		String des, String orderby, int pageNo, Handler handler) throws ClientException
    {
    	FolderSearchRequestV2 request = new FolderSearchRequestV2();
        request.setLimit(ClientConfig.CLOUD_COUNT_PER_PAGE);
        request.setOffset(pageNo*ClientConfig.CLOUD_COUNT_PER_PAGE);
        request.setOwnerID(ownerId);
    	request.setName(keyWords);
    	final FolderListResponseV2 response = FolderClientV2.getInstance().search(request,
                this.getAuthCode());
    	return translateNode(response, pageNo);
    }
    		
    		
    @Override
    public PagedList<FileFolderInfo> getNodeListFromServer(final Context context, String ownerId, String folderID,
        String des, String orderby, int pageNo, Handler handler) throws ClientException
    {
        FolderListRequestV2 request = new FolderListRequestV2();
        request.setFolderID(folderID);
        request.setLimit(ClientConfig.CLOUD_COUNT_PER_PAGE);
        request.setOffset(pageNo*ClientConfig.CLOUD_COUNT_PER_PAGE);
        request.setOwnerID(ownerId);
        
        List<Order> olist = new ArrayList<Order>();
        olist.add(new Order("type","ASC"));
        request.setOrder(olist);
        final FolderListResponseV2 response = FolderClientV2.getInstance().getFolderInfoList(request,
            this.getAuthCode());
        return translateNode(response,pageNo);
    }
    
    private PagedList<FileFolderInfo> translateNode(FolderListResponseV2 response, int pageNo){
    	PagedList<FileFolderInfo> pagedList = new PagedList<FileFolderInfo>();
        List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
        if (null != response)
        {
            if (null != response.getFolders())
            {
            	List<FolderResponse> serverList = response.getFolders();
            	List<FolderInfo> translateList = new ArrayList<FolderInfo>(serverList.size());
            	FolderInfo tmpFolder = null;
            	for(FolderResponse item : serverList){
            		tmpFolder = new FolderInfo();
            		tmpFolder.valueOf(item);
            		translateList.add(tmpFolder);
            	}
//            	folderInfoList = DAOFactory.instance(context)
//                        .getFolderDao()
//                        .getFolderListByPage(pageNo, ClientConfig.CLOUD_COUNT_PER_PAGE, folderID, "asc", IBaseDao.id);
//                FileSyncComparator.syncFolderToLocal(context, response.getFolders(), folderInfoList, folderID);
                fileFolderInfoList.addAll(translateList);
            }
            if (null != response.getFiles())
            {
//            	fileInfoList = DAOFactory.instance(context)
//                        .getFileDao()
//                        .getFileListByPage(pageNo, ClientConfig.CLOUD_COUNT_PER_PAGE, folderID, "asc", IBaseDao.id);
//            	FileSyncComparator.syncFileToLocal(context,
//                    response.getFiles(),
//                    fileInfoList,
//                    folderID);
            	List<FileInfoResponseV2> serverList = response.getFiles();
            	List<FileInfo> translateList = new ArrayList<FileInfo>(serverList.size());
            	FileInfo tmpFile = null;
            	for(FileInfoResponseV2 item : serverList){
            		tmpFile = new FileInfo();
            		tmpFile.valueOf(item);
            		translateList.add(tmpFile);
            	}
            	fileFolderInfoList.addAll(translateList);
            }
            pagedList.setTotal(response.getTotalCount());
            pagedList.setPagedList(fileFolderInfoList);
            pagedList.setPageNumber(pageNo);
        }
        return pagedList;
    }
    
    private synchronized List<FileFolderInfo> getServerFileFolderListPage(final Context context,
    		final String ownerId, final String folderID, final String des, final String orderby,
        List<FileFolderInfo> fileFolderInfoList, long nowTime, Handler handler)
    {
        try
        {
        	shareDriveApplication.smartAuthorization();
            final FolderListRequestV2 request = new FolderListRequestV2();
            request.setFolderID(folderID);
            request.setLimit(ClientConfig.CLOUD_COUNT_PER_PAGE);
            request.setOffset(ShareDriveApplication.getInstance().getMyCloudDrivePage()
                * ClientConfig.CLOUD_COUNT_PER_PAGE);
            request.setOwnerID(ownerId);
            
            Order o = new Order();
            o.setDirection(des);
            o.setField(orderby);
            List<Order> olist = new ArrayList<Order>();
            olist.add(o);
            request.setOrder(olist);
            
            final FolderListResponseV2 response = FolderClientV2.getInstance().getFolderInfoList(request,
                this.getAuthCode());
            
            List<FileFolderInfo> folderList = FileHelper.convertFolderRemoteToLocal(response);
            List<FileFolderInfo> fileList = FileHelper.convertFileRemoteToLocal(response);
            fileFolderInfoList.addAll(folderList);
            fileFolderInfoList.addAll(fileList);
            new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        request.setLimit(1000);
                        request.setOffset(0);
                        FolderListResponseV2 responseAll = FolderClientV2.getInstance()
                            .getFolderInfoList(request, RemoteFileService.this.getAuthCode());
                        List<FolderInfo> folderInfoList = DAOFactory.instance(context)
                            .getFolderDao()
                            .getFolderList(ownerId, folderID);
                        List<FileInfo> fileInfoList = DAOFactory.instance(context)
                            .getFileDao()
                            .getFileList(ownerId, folderID);
                        FileHelper.compareServiceClientFolder(context,
                            responseAll.getFolders(),
                            folderInfoList, ownerId, folderID);
                        FileHelper.compareServiceClientFile(context,
                            responseAll.getFiles(),
                            fileInfoList,
                            ownerId, folderID);
                    }
                    catch (Exception e)
                    {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                }
            }).start();
            DAOFactory.instance(context).getFolderDao().updateLastRefreshTime(ownerId, folderID, nowTime);
        }
        catch (ClientException e)
        {
            // TODO: handle exception
            LogUtil.i(TAG, "getServerFileFolderListPage e:" + e.getStatusCode());
            Message msg = new Message();
            msg.what = ClientConfig.FAILTOOBTAINLIST;
            msg.obj = e.getStatusCode();
            handler.sendMessage(msg);
            e.printStackTrace();
        }
        
        return fileFolderInfoList;
    }
    
    @Override
    public synchronized List<FileFolderInfo> getFileFolderList(Context context, String ownerId, String folderID)
    {
        List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
        List<FolderInfo> folderInfoList = null;
        List<FileInfo> fileInfoList = null;
        folderInfoList = DAOFactory.instance(context).getFolderDao().getFolderList(ownerId, folderID);
        fileFolderInfoList.addAll(folderInfoList);
        fileInfoList = DAOFactory.instance(context).getFileDao().getFileList(ownerId, folderID);
        fileFolderInfoList.addAll(fileInfoList);
        
        return fileFolderInfoList;
    }
    
    @Override
    public synchronized List<FileFolderInfo> getFileFolderListPage(Context context, FileFolderInfo folder)
    {
        List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
        List<FolderInfo> folderInfoList = null;
        List<FileInfo> fileInfoList = null;
        folderInfoList = DAOFactory.instance(context)
            .getFolderDao()
            .getFolderListPage(folder.getOwnerId(), folder.getId(),Constant.MYCLOUD_GET_FILE_LIST_STATE);
        fileFolderInfoList.addAll(folderInfoList);
        fileInfoList = DAOFactory.instance(context)
            .getFileDao()
            .getFileListPage(folder.getOwnerId(), folder.getId(), Constant.MYCLOUD_GET_FILE_LIST_STATE);
        fileFolderInfoList.addAll(fileInfoList);
        
        return fileFolderInfoList;
    }
    
    @Override
    public synchronized List<FileFolderInfo> getSharedFileFolderList(boolean autoManualFlag, Context context,
        FileFolderInfo folder, String des, int limit, int offset, String orderby, String shareOwnerId)
        throws ClientException
    {
    	shareDriveApplication.smartAuthorization();
        List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
        List<FolderInfo> folderInfoList = null;
        List<FileInfo> fileInfoList = null;
        String folderID = folder.getId();
        long lastRefreshTime = DAOFactory.instance(context).getFolderDao().getLastRefreshTime(folder.getOwnerId(), folderID);
        long nowTime = System.currentTimeMillis();
        SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
        boolean isOnline = settings.getBoolean(ClientConfig.INTERNETSTATE, false);
        if (isOnline && (!autoManualFlag || (1 * 60 * 1000 < nowTime - lastRefreshTime)))
        {
            LogUtil.i(TAG, "Get server file&folder shared list...");
            FolderListRequestV2 request = new FolderListRequestV2();
            request.setFolderID(folderID);
            request.setLimit(ClientConfig.SHARED_COUNT_PER_PAGE);
            request.setOffset(ShareDriveApplication.getInstance().getMySharePage()
                * ClientConfig.SHARED_COUNT_PER_PAGE);
            request.setOwnerID(folder.getOwnerId());
            
            Order o = new Order();
            o.setDirection(des);
            o.setField(orderby);
            List<Order> olist = new ArrayList<Order>();
            olist.add(o);
            request.setOrder(olist);
            
            final FolderListResponseV2 response = FolderClientV2.getInstance().getFolderInfoList(request,
                this.getAuthCode());
            
            List<FileFolderInfo> folderList = FileHelper.convertFolderRemoteToLocal(response);
            List<FileFolderInfo> fileList = FileHelper.convertFileRemoteToLocal(response);
            fileFolderInfoList.addAll(folderList);
            fileFolderInfoList.addAll(fileList);
            folderInfoList = DAOFactory.instance(context).getFolderDao().getFolderList(folder.getOwnerId(), folderID);
            fileInfoList = DAOFactory.instance(context).getFileDao().getFileList(folder);
            FileHelper.compareServiceClientFolder(context, response.getFolders(), folderInfoList, folder.getOwnerId(), folderID);
            FileHelper.compareServiceClientFile(context, response.getFiles(), fileInfoList, folder.getOwnerId(), folderID);
            DAOFactory.instance(context).getFolderDao().updateLastRefreshTime(folder.getOwnerId(), folderID, nowTime);
        }
        fileFolderInfoList.clear();
        folderInfoList = DAOFactory.instance(context).getFolderDao().getFolderList(folder.getOwnerId(), folderID);
        fileFolderInfoList.addAll(folderInfoList);
        fileInfoList = DAOFactory.instance(context).getFileDao().getFileList(folder);
        fileFolderInfoList.addAll(fileInfoList);
        
        return fileFolderInfoList;
    }
    
    @Override
    public String logout() throws ClientException
    {
        // TODO Auto-generated method stub
        String res = "";
        shareDriveApplication.smartAuthorization();
        res = userClient.deleteToken(this.getAuthCode());
        return res;
    }
    
    @Override
    public UserResponseV2 login(Context context, String userName, String password) throws ClientException
    {
        // TODO Auto-generated method stub
        UserResponseV2 response = UserControl.Login(context, userName, password);
        return response;
    }
    
    @Override
    public List<FileFolderInfo> getMoveFolderDB(Context context, String ownerId, String folderID, String excption)
        throws ClientException
    {
        // TODO Auto-generated method stub
        
        List<FileFolderInfo> fileFolderInfoList = new ArrayList<FileFolderInfo>();
        List<FolderInfo> folderInfoList = null;
        folderInfoList = DAOFactory.instance(context).getFolderDao().getFolderList(ownerId, folderID);
        if (null != excption)
        {
            for (int i = 0; i < folderInfoList.size(); i++)
            {
                if (excption.equals(folderInfoList.get(i).getId()))
                {
                    folderInfoList.remove(i);
                }
            }
        }
        fileFolderInfoList.addAll(folderInfoList);
        return fileFolderInfoList;
    }
    
    @Override
    public void downloadThumbnailIcon(String ownerBy, String fileId, String iconPath, IDownloadThumbnailCallback callback)
    {
        // TODO Auto-generated method stub
        try
        {
        	shareDriveApplication.smartAuthorization();
            new Thread(new DownloadThumbnailTask(this.getAuthCode(), ownerBy, fileId, iconPath,
                callback)).start();
        }
        catch (Exception e)
        {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    
    @Override
    public void downloadShareThumbnailIcon(String ownerID, String fileId, String iconPath,
        IDownloadThumbnailCallback callback)
    {
        // TODO Auto-generated method stub
        try
        {
        	shareDriveApplication.smartAuthorization();
            new Thread(new DownloadThumbnailTask(this.getAuthCode(), ownerID, fileId, iconPath, callback)).start();
        }
        catch (Exception e)
        {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    
    @Override
    public void shareFileSaveMyCloud(final String targetOwnerId, final String srcOwnerId, final String destFolderId,
        final List<String> srcFileIdList, final IFileRemoteServiceCallback callback)
    {
        // TODO Auto-generated method stub
        final AsyncTaskHandler handler = new AsyncTaskHandler()
        {
            @Override
            public void onSuccess()
            {
                // TODO Auto-generated method stub
                if (null != callback)
                {
                    callback.onSuccess();
                }
            }
            
            @Override
            public void onFailure(ClientException exception)
            {
                // TODO Auto-generated method stub
                if (null != callback)
                {
                    callback.onFailure(exception.getMessage());
                }
            }
            
            @Override
            public void onExecuting()
            {
                // TODO Auto-generated method stub
                if (null != callback)
                {
                    callback.onExecuting();
                }
            }
        };
        
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                // TODO Auto-generated method stub
                try
                {
                    //
                    ArrayList<AsyncTaskINodeRequest> srcNodeList = new ArrayList<AsyncTaskINodeRequest>();
                    for (String fileId : srcFileIdList)
                    {
                        AsyncTaskINodeRequest folderToCopy = new AsyncTaskINodeRequest();
                        folderToCopy.setSrcNodeId(Long.valueOf(fileId));
                        srcNodeList.add(folderToCopy);
                    }
                	shareDriveApplication.smartAuthorization();
                    //
                    AsyncTaskRequest request = new AsyncTaskRequest();
                    request.setType("copy");
                    request.setDestOwnerId(Long.valueOf(targetOwnerId));
                    request.setSrcOwnerId(Long.valueOf(srcOwnerId));
                    request.setDestFolderId(Long.valueOf(destFolderId));
                    request.setSrcNodeList(srcNodeList);
                    request.setAutoRename(true);
                    FileClientV2.getInstance().copyFileAsy(RemoteFileService.this.getAuthCode(),
                        request,
                        handler);
                    //
                }
                catch (Exception e)
                {
                    // TODO: handle exception
                    e.printStackTrace();
                    if (null != callback)
                    {
                        callback.onFailure(e.getMessage());
                    }
                }
            }
        }).start();
    }
    
    @Override
    public void shareFileSaveMyCloud(final String srcOwnerId, final String destOwnerId, final String destFolderId,
    		final String srcFileId, final IFileRemoteServiceCallback callback)
    {
        // TODO Auto-generated method stub
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                // TODO Auto-generated method stub
                try
                {
                	shareDriveApplication.smartAuthorization();
                    //
                    if (null != callback)
                    {
                        callback.onExecuting();
                    }
                    CopyFileRequestV2 request = new CopyFileRequestV2();
                    // request.setDestParent(destFolderId);
                    request.setAutoRename(true);
                    request.setDestOwnerId(Long.valueOf(destOwnerId));
                    request.setDestParent(Long.valueOf(destFolderId));
                    request.setLink(null);
                    FileInfoResponseV2 response = FileClientV2.getInstance()
                        .copyFile(srcOwnerId,
                            srcFileId,
                            RemoteFileService.this.getAuthCode(),
                            request);
                    if (null == response)
                    {
                        LogUtil.e(TAG, "[shareFileSaveMyCloud]response == null !!!");
                    }
                    if (null != callback)
                    {
                        callback.onSuccess();
                    }
                    //
                }
                catch (Exception e)
                {
                    // TODO: handle exception
                    e.printStackTrace();
                    if (null != callback)
                    {
                        callback.onFailure(e.getMessage());
                    }
                }
            }
        }).start();
    }
    
    @Override
    public ServerUrlV2 getServerAddress(String type) throws ClientException
    {
    	shareDriveApplication.smartAuthorization();
        return userClient.getServerAddress(this.getAuthCode(), type);
    }

	@Override
	public boolean isFileUpdate(Context context, FileFolderInfo info)
			throws ClientException {
    	shareDriveApplication.smartAuthorization();
		FileInfoResponseV2 fileObj = this.getFileResponse(info);
		if(fileObj != null)
		{
			FileInfo localFileObj = ServiceFactory.instance(context)
            .getLocalFileService().getFileById(info);
			if(localFileObj != null)
			{
				return FileHelper.isFileUpdate(context, fileObj, info);
			}
			return true;
		}
		return true;
	}

}
